/*
 * Copyright 2016 Stuart Kent
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.example.mybugshaker.flow.email.screenshot;

import com.example.mybugshaker.utils.Logger;
import io.reactivex.Observable;
import ohos.app.Context;
import ohos.app.Environment;
import ohos.media.image.ImagePacker;
import ohos.media.image.PixelMap;
import ohos.utils.net.Uri;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;

public final class ScreenshotUriObservable {
//    private static final String AUTHORITY_SUFFIX = ".bugshaker.fileprovider";
    private static final String SCREENSHOTS_DIRECTORY_NAME = "bugshaker-internal";
    private static final String SCREENSHOT_FILE_NAME = "latest-screenshot.jpg";
    private static final int JPEG_COMPRESSION_QUALITY = 90;

    /* default */ public static Observable<Uri> create(
            @NotNull final Context applicationContext,
            @NotNull final PixelMap pixelMap,
            @NotNull final Logger logger) {

        return Observable.create(subscriber->{

            final File screenshotFile = getScreenshotFile(applicationContext);

            FileOutputStream outputStream = new FileOutputStream(screenshotFile);

            ImagePacker imagePacker = ImagePacker.create();
            ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
            packingOptions.format = "image/jpeg";
            packingOptions.quality = JPEG_COMPRESSION_QUALITY ;
            boolean result = imagePacker.initializePacking(outputStream, packingOptions);

            result = imagePacker.addImage(pixelMap);
//            long dataSize = imagePacker.finalizePacking();

            outputStream.flush();

            final Uri uri = Uri.getUriFromFile(screenshotFile);

            logger.d("Screenshot Uri created: " + result);

            subscriber.onNext(uri);
            subscriber.onComplete();
        });
    }

    private ScreenshotUriObservable() {
        // This constructor intentionally left blank.
    }

    public static File getScreenshotFile(@NotNull final Context applicationContext) {

        final File screenshotsDir = new File(applicationContext.getExternalFilesDir( Environment.DIRECTORY_PICTURES).getPath(), SCREENSHOTS_DIRECTORY_NAME);
        screenshotsDir.mkdirs();
        return new File(screenshotsDir, SCREENSHOT_FILE_NAME);
    }

}
